<?php echo $html->script(array("jquery.validate.js", "jquery.form.js")); ?>
<script type="text/javascript">
    jQuery(document).ready(function(){
        //Populate City drop down on change State drop down
        jQuery("#AddressBookFieldStateId").live('change',function () {
            var stateId=jQuery(this).val();
            var URL="<?php echo Configure::read('base_url'); ?>users/loadCityAddress/"+stateId;          
            jQuery("#AddressBookFieldCityId").html("<option value='0'>loading...</option>");
            jQuery("#userCityIdWrapper").load(URL);        
        });
        //Populate State drop down on change Country dropdown
        jQuery("#AddressBookFieldCountryId").live('change',function () {
            var countryId=jQuery(this).val();
            var URL="<?php echo Configure::read('base_url'); ?>users/loadStateAddress/"+countryId;          
            jQuery("#AddressBookFieldStateId").html("<option value='0'>loading...</option>");
            jQuery("#userStateIdWrapper").load(URL);        
        });
        jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
            phone_number = phone_number.replace(/\s+/g, "");
            return this.optional(element) || phone_number.length > 9 &&
                phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
        }, "Please specify a valid phone number");

        jQuery.validator.addMethod("postalcode", function(postalcode, element) {
            return this.optional(element) || postalcode.match(/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXYabceghjklmnpstvxy]{1}\d{1}[A-Za-z]{1} ?\d{1}[A-Za-z]{1}\d{1})$/);
        }, "Please specify a valid postal/zip code");

    });

    jQuery(":submit").live('click', function(){
        ajaxSubmitForm.selector=jQuery(this).closest('.addressForm');
        ajaxSubmitForm.submitForm();
    });

    jQuery('.addNew').live('click', function(){
        radioFunctions.addNew(jQuery(this));
        jQuery(this).removeAttr('checked');
        return false;
    });
    jQuery('.btn-radio, input[name="editButton"], input[name="cancelButton"]').live('click', function(){
        radioFunctions.selector=jQuery(this).val()=="Cancel" ? jQuery(this).closest('table').prev().find('.btn-radio') : jQuery(this);
        radioFunctions.accordian();
    });

    jQuery('input[name="deleteButton"]').live('click', function(){
        var selectedForm=jQuery(this).closest('form');
        var dataString=selectedForm.serialize();
        if(confirmDelete()===false){
            return false;
        }
        jQuery.ajax({
            type: "post",
            url: baseurl+"users/my_address_book_delete",
            data: dataString,
            success: function(){
                selectedForm.parent().parent().remove();
            }
        });
    });
    jQuery('.proced').live('click', function(){
        if(jQuery('[name="data[AddressBook][address_book_name]"]:checked').next().val()!=""){
            dataString=jQuery('[name="data[AddressBook][address_book_name]"]:checked').closest('form').find('[name="data[AddressBook][id]"]').val();
            jQuery.ajax({
                type: "post",
                url: baseurl+"users/my_address_book_select/"+dataString,
                success: function(data){
                    window.location="<?php
if ($proced === true) {
    echo $_SERVER['HTTP_REFERER'];
}
?>";
                 
                }
            });
        }else{
            alert("Please save address first");
        }

    });

    var ajaxSubmitForm={
        submitForm: function(){
       
            jQuery(ajaxSubmitForm.selector).validate({
                rules: {
                    "data[AddressBookField][phone]": {
                        required: true,
                        phoneUS: true
                    },
                    "data[AddressBookField][zip]":{
                        required: true,
                        postalcode: true
                    }
                },
            
                submitHandler: function(form) {
                    jQuery(ajaxSubmitForm.selector).fadeOut();
                    ajaxSubmitForm.showLoader();
                    jQuery(ajaxSubmitForm.selector).remove();
                
                    jQuery(form).ajaxSubmit({
                        url: baseurl+"users/my_address_book_save",
                        type: "post",
                        dataType: "html",
                    
                        success: function(data){
                            //newForm=ajaxSubmitForm.replaceOldFromValue(data);
                            jQuery(data).insertAfter('.loading').fadeIn();
                            ajaxSubmitForm.removeLoader();

                        }
                    });
                }

            });
        },

        showLoader: function(){
            jQuery('<img src="<?php echo $this->webroot; ?>img/loading.gif" alt="loading" class="loading" />').insertAfter(ajaxSubmitForm.selector);

        },
        removeLoader: function(){
            jQuery('.loading').remove();
        },
        replaceOldFromValue: function(data){
            selector = jQuery('.newForm').children('*').clone();
            jQuery.each(data.AddressBookField, function(name, value){
                selector.find('[name="data[AddressBookField]['+ name +']"]').text(value);   //selector.find('[name="data[AddressBookField]['+ name +']"]').val(value);
            });

            content=jQuery('<input type="hidden" name="data[AddressBook][id]" value="'+ data.AddressBook.id +'" /><input type="hidden" name="data[AddressBookField][id]" value="'+ data.AddressBookField.id +'" />');
            selector.find('.addressForm').append(content);
            alert(selector.html());
            return selector;
        }
    }

    var radioFunctions={
        addNew: function(selector){
            var content=jQuery('.newForm').children('*').clone();
            /*content.find("input:text").each(function(){
                newValue='Enter '+jQuery(this).prev().text();
                jQuery(this).val(newValue);
            }); */

            //content.find("input:radio").val("Enter Address Name");
            content.find("input:radio").next().remove();
            jQuery('<input name="data[AddressBook][address_book_name]" type="text"  size="30" value="Enter Address Title" onfocus="clearValue(this)" onblur="populateDefalutValue(this)" class="required" />')
            .insertAfter(content.find("input:radio"));
            jQuery(content).insertBefore(selector.parent().parent());
        },
        accordian: function(){
            tableHidden=radioFunctions.selector.closest('table').next();
            if(tableHidden.hasClass('hiddenTable')==true){
                tableHidden.removeClass('hiddenTable');
                tableHidden.slideDown();
                jQuery('.btn-radio').removeAttr('checked');
                tableHidden.prev().find('.btn-radio').attr('checked', true);
                radioFunctions.selector.closest('table').find('.edit').fadeOut();
                radioFunctions.inlineEdit();
            } else{
                tableHidden.slideUp();
                tableHidden.addClass('hiddenTable');
                radioFunctions.selector.removeAttr('checked');
                radioFunctions.selector.closest('table').find('.edit').fadeIn();
                radioFunctions.inlineSet();
            }
        },
        inlineEdit: function(){
            selectedLabel=radioFunctions.selector.closest('tr').find('label');
            labelText=selectedLabel.text();
            selectedLabel.parent().append('<input name="data[AddressBook][address_book_name]" type="text"  size="30" value="'+ labelText +'" class="required"/>');
            selectedLabel.remove();

        },
        inlineSet: function(){
            selectedInput=radioFunctions.selector.closest('tr').find('input:text[name="data[AddressBook][address_book_name]"]');
            selectedInputValue=selectedInput.prev().val();
            jQuery('<label>'+ selectedInputValue +'</label>').insertBefore(selectedInput);
            selectedInput.remove();
        }
    }
    function confirmDelete(){
        var con=confirm('Do you really want to delete it?');
        if(con=== false){
            return false;
        }
    }

    function clearValue(param){
        if(param.value=="Enter Address Title"){
            param.value='';
        }
    }
    function populateDefalutValue(param){
        if(param.value==''){
            param.value='Enter Address Title';
        }

    }
</script>
<style type="text/css">
    .search-title{font-weight: normal;color: #000;padding: 0px;}
    .search-title label{color: #000;}
    .hiddenTable{display: none;}
    .newForm{display: none;}
</style>
<?php $this->Html->addCrumb('My Address Book'); ?>
<div class="innercon" style="margin-bottom:5px;">
    <!--End Left Navigation-->
    <div class="global-title">Your Address Book – Select an address</div>
    <div id="result">
        <table width="100%" border="0" cellspacing="0" cellpadding="0" class="address-table">
<?php if (!empty($addresses)): ?>
    <?php foreach ($addresses as $address): ?>
                    <tr>
                        <td>
                            <form action="" method="post" class="addressForm">
                                <input type="hidden" name="data[AddressBook][id]" value="<?php echo $address['AddressBook']['id']; ?>" />
                                <input type="hidden" name="data[AddressBookField][id]" value="<?php echo $address['AddressBookField']['id']; ?>" />
                                <table style="background-color: #D6DBDE; width: 1000px;">
                                    <tr>
                                        <td><input name="data[AddressBook][address_book_name]" type="radio" value="<?php echo $address['AddressBook']['address_book_name']; ?>" class="btn-radio" /><label><?php echo $address['AddressBook']['address_book_name'] ?></label></td>
                                        <td width="5%" class="last-col"><input name="deleteButton" type="button" value="Delete" class="button" /></td>
                                        <td width="5%" class="last-col"><input name="editButton" type="button" value="Edit" class="button" /></td>
                                    </tr>
                                </table>

                                <table width="990" border="0" cellspacing="0" cellpadding="0" style="margin:0 0 0 20px;" class="hiddenTable">
                                    <tr>
                                        <td width="33%"><label class="first-label">First name <em>*</em> :</label> <input name="data[AddressBookField][first_name]" type="text"  size="30" class="first-field required" value="<?php echo $address['AddressBookField']['first_name']; ?>" /></td>
                                        <td width="32%"><label class="first-label">Last name <em>*</em> :</label> <input name="data[AddressBookField][last_name]" type="text"  size="30" class="first-field required" value="<?php echo $address['AddressBookField']['last_name']; ?>" /></td>
                                        <td width="25%">&nbsp;</td>
                                        <td width="5%" class="last-col"><input name="saveButton" type="submit" value="Save" class="button" /></td>
                                    </tr>
                                    <tr>
                                        <td width="33%"><label class="first-label">Address Line 1<em>*</em> :</label> <input name="data[AddressBookField][address_line_1]" type="text"  size="30" class="first-field required" value="<?php echo $address['AddressBookField']['address_line_1']; ?>" /></td>
                                        <td width="32%">&nbsp;</td>
                                        <td width="25%">&nbsp;</td>
                                        <td width="5%" class="last-col"><input class="button" name="cancelButton" type="reset" value="Cancel" /></td>
                                    </tr>
                                    <tr>
                                        <td width="33%"><label class="first-label">Address Line 2:</label> <input name="data[AddressBookField][address_line_2]" type="text"  size="30" class="first-field" value="<?php echo $address['AddressBookField']['address_line_2']; ?>" /></td>
                                        <td width="32%">&nbsp;</td>
                                        <td width="25%">&nbsp;</td>
                                        <td width="5%" class="last-col">&nbsp;</td>
                                    </tr>
                                    <tr>
                                        <td width="33%"><label class="first-label">City <em>*</em> :</label> 
                                            <script type="text/javascript">
                                                jQuery(document).ready(function(){
                                                    //Populate City drop down
                                                    var URL="<?php echo Configure::read('base_url'); ?>users/loadCityAddress/<?php echo $address['AddressBookField']['state_id']; ?>/<?php echo $address['AddressBookField']['id']; ?>/<?php echo $address['AddressBookField']['city_id']; ?>";
                                                    jQuery("#userCityIdWrapper_<?php echo $address['AddressBookField']['id'];?>").load(URL);
                                                    //Populate State drop down
                                                    var URL_state="<?php echo Configure::read('base_url'); ?>users/loadStateAddress/<?php echo $address['AddressBookField']['country_id']; ?>/<?php echo $address['AddressBookField']['id']; ?>/<?php echo $address['AddressBookField']['state_id']; ?>";
                                                    jQuery("#userStateIdWrapper_<?php echo $address['AddressBookField']['id']; ?>").load(URL_state);2                                                     
                                                    //Populate City drop down on change State drop down
                                                    jQuery("#AddressBookFieldStateId_<?php echo $address['AddressBookField']['id']; ?>").live('change',function () {
                                                        var stateId=jQuery(this).val();
                                                        var URL="<?php echo Configure::read('base_url'); ?>users/loadCityAddress/"+stateId+"/<?php echo $address['AddressBookField']['id']; ?>";          
                                                        jQuery("#AddressBookFieldCityId_<?php echo $address['AddressBookField']['id']; ?>").html("<option value='0'>loading...</option>");
                                                        jQuery("#userCityIdWrapper_<?php echo $address['AddressBookField']['id']; ?>").load(URL);        
                                                    });
                                                    //Populate State drop down on change Country dropdown
                                                    jQuery("#AddressBookFieldCountryId_<?php echo $address['AddressBookField']['id']; ?>").live('change',function () {
                                                        var countryId=jQuery(this).val();
                                                        var URL="<?php echo Configure::read('base_url'); ?>users/loadStateAddress/"+countryId+"/<?php echo $address['AddressBookField']['id']; ?>";          
                                                        jQuery("#AddressBookFieldStateId_<?php echo $address['AddressBookField']['id']; ?>").html("<option value='0'>loading...</option>");
                                                        jQuery("#userStateIdWrapper_<?php echo $address['AddressBookField']['id']; ?>").load(URL);        
                                                    });
                                                });
                                            </script>
                                            <div id="userCityIdWrapper_<?php echo $address['AddressBookField']['id'];?>"></div>
                                        </td>
                                        <td width="32%">
                                            <label class="first-label">State <em>*</em> :</label>
                                            <div id="userStateIdWrapper_<?php echo $address['AddressBookField']['id'];?>"></div>        
                                        </td>
                                        <td width="30%"><label class="first-label">Zip <em>*</em> :</label> <input name="data[AddressBookField][zip]" type="text"  size="30" class="first-field" value="<?php echo $address['AddressBookField']['zip']; ?>" /></td>
                                        <td width="5%" class="last-col">&nbsp;</td>
                                    </tr>
                                    <tr>
                                        <td width="33%"><label class="first-label">Country <em>*</em> :</label>
                                            <?php
                                            echo $this->Form->input('AddressBookField.country_id', array('id'=>'AddressBookFieldCountryId_'.$address['AddressBookField']['id'],'label' => false, 'div' => false, 'class' => 'required', 'empty' => 'Select Country', 'selected' => $address['AddressBookField']['country_id'],'style'=>'width:185px'));
                                            ?>

                                        </td>
                                        <td width="32%"><label class="first-label">Phone <em>*</em> :</label> <input name="data[AddressBookField][phone]" type="text"  size="30" class="first-field" value="<?php echo $address['AddressBookField']['phone']; ?>" /></td>
                                        <td width="25%"><label class="first-label">Email <em>*</em> :</label> <input name="data[AddressBookField][email]" type="text"  size="30" class="first-field email required" value="<?php echo $address['AddressBookField']['email']; ?>" /></td>
                                        <td width="5%" class="last-col">&nbsp;</td>
                                    </tr>
                                </table>
                            </form>

                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>

<?php endif; ?>

            <tr>
                <td><input name="radio-btn" type="radio" value="" class="btn-radio addNew" /><label>Add New Address</label></td>
            </tr>

            <tr>
                <td style="text-align: right">
                    <?php if ($proced === true) { ?>
                        <input name="proced" type="button" value="Select & Proceed" class="button proced" />
                    <?php } else { ?>
                        <input name="proced" type="button" value="Select & Proceed" class="button" />
<?php } ?>
                </td>
            </tr>

        </table>
    </div>
    <!--End Product-->
</div>


<table class="newForm">
    <tr>    
        <td>
            <form action="" method="post" class="addressForm">
                <table style="background-color: #D6DBDE; width: 1000px;">
                    <tr>
                        <td width="90%"><input name="data[AddressBook][address_book_name]" type="radio" value="" class="btn-radio" /><input name="data[AddressBook][address_book_name]" type="text" value="" class="required" /></td>
                        <td width="5%" class="last-col"><input name="deleteButton" type="button" value="Delete" class="button" /></td>
                        <td width="5%" class="last-col"><input name="editButton" type="button" value="Edit" class="button" /></td>
                    </tr>
                </table>
                <table width="990" border="0" cellspacing="0" cellpadding="0" style="margin:0 0 0 20px;">
                    <tr>
                        <td width="33%"><label class="first-label">First name <em>*</em> :</label> <input name="data[AddressBookField][first_name]" type="text"  size="30" class="first-field required" value="" /></td>
                        <td width="32%"><label class="first-label">Last name <em>*</em> :</label> <input name="data[AddressBookField][last_name]" type="text"  size="30" class="first-field required" value="" /></td>
                        <td width="25%">&nbsp;</td>
                        <td width="5%" class="last-col"><input name="saveButton" type="submit" value="Save" class="button" /></td>
                    </tr>
                    <tr>
                        <td width="33%"><label class="first-label">Address Line 1<em>*</em> :</label> <input name="data[AddressBookField][address_line_1]" type="text"  size="30" class="first-field required" value="" /></td>
                        <td width="32%">&nbsp;</td>
                        <td width="25%">&nbsp;</td>
                        <td width="5%" class="last-col"><input name="deleteButton" type="reset" value="Cancel" class="button" /></td>
                    </tr>
                    <tr>
                        <td width="33%"><label class="first-label">Address Line 2:</label> <input name="data[AddressBookField][address_line_2]" type="text"  size="30" class="first-field" value="" /></td>
                        <td width="32%">&nbsp;</td>
                        <td width="25%">&nbsp;</td>
                        <td width="5%" class="last-col">&nbsp;</td>
                    </tr>
                    <tr>
                        <td width="33%"><label class="first-label">City <em>*</em> :</label> 
                            <div id="userCityIdWrapper">
                                <?php echo $this->Form->input('AddressBookField.city_id', array('label' => false, 'div' => false, 'class' => 'required','style'=>'width:185px')); ?>
                            </div>
                        </td>
                        <td width="32%"><label class="first-label">State <em>*</em> :</label> 
                            <div id="userStateIdWrapper">
                                <?php echo $this->Form->input('AddressBookField.state_id', array('label' => false, 'div' => false,'style'=>'width:185px'));?>
                            </div>
                        </td>
                        <td width="33%"><label class="first-label">Zip <em>*</em> :</label> <input name="data[AddressBookField][zip]" type="text"  size="30" class="first-field" value="" /></td>
                        <td width="5%" class="last-col">&nbsp;</td>
                    </tr>
                    <tr>
                        <td width="33%"><label class="first-label">Country <em>*</em> :</label> 
                            <?php
                            echo $this->Form->input('AddressBookField.country_id', array('label' => false, 'div' => false, 'class' => 'required', 'selected' => 223,'style'=>'width:185px'));
                            ?>
                        </td>
                        <td width="32%"><label class="first-label">Phone <em>*</em> :</label> <input name="data[AddressBookField][phone]" type="text"  size="30" class="first-field" value="" /></td>
                        <td width="33%"><label class="first-label">Email <em>*</em> :</label> <input name="data[AddressBookField][email]" type="text"  size="30" class="first-field email required" value="" /></td>
                        <td width="5%" class="last-col">&nbsp;</td>
                    </tr>
                </table>
            </form>

        </td>
    </tr>
</table>